<template>
  <div class="pay-container">
    <!-- 生成微信支付二维码 -->
    <div class="erwei">
      <img :src="qrUrl" alt="" />
    </div>
    <svg class="icon" aria-hidden="true">
      <use xlink:href="#icon-wechat_pay"></use>
    </svg>
    <span>使用微信进行支付</span>
    <el-descriptions title="订单详情">
      <el-descriptions-item label="订单号">
        {{ order.order_id }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ order.create_time }}
      </el-descriptions-item>
      <el-descriptions-item label="产品名称">
        {{ order_detail.productName }}
      </el-descriptions-item>
      <el-descriptions-item label="商品描述">
        {{ order_detail.description }}
      </el-descriptions-item>
      <el-descriptions-item label="购买数量">
        {{ order_detail.quantity }}
      </el-descriptions-item>
      <el-descriptions-item label="购买用户">
        {{ order.user_nickname }}
      </el-descriptions-item>
      <el-descriptions-item label="地址">
        {{ order.address }}
      </el-descriptions-item>
      <el-descriptions-item label="手机号">
        {{ order.user_phone }}
      </el-descriptions-item>
      <el-descriptions-item label="总价格">
        {{ order.total_fee }}
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template> 
<script>
import * as payApi from "@/api/pay";
//首先获取订单的id
// import { mapState } from "vuex";
//引入生成二维码插件
import qr from "qrcode";
export default {
  data() {
    return {
      qrUrl: "", //支付二维码地址
      order_detail: {},//订单详情
      payUrlRes: {},
      payUrl: "",
      order: {},
      order_id: "",
    };
  },

  methods: {
    queryOrderStatus() {
      //使用定时器进行轮询发送请求
      this.queryInterval = setInterval(async () => {
        let res = await payApi.queryOrderStatus(this.order_id);
        console.log(res);
        if(res.data.status===200){
          //支付成功，跳转至支付成功的页面
          // console.log(11)
          this.$router.push({name:'paysuccess'})
        }
      }, 1000);
    },
  },
  // computed:{

  // },
  async created() {
    let order_id = this.$route.query.order_id;
    this.order_id = order_id;

    if (!order_id) {
      this.$router.push("/vipmanager/charge");
      return;
    }

    let res = await Promise.all([
      payApi.getOrder(order_id),
      payApi.startPay(order_id),
    ]);

    //发起轮询查询结果
    this.queryOrderStatus()


    console.log(res);
    //订单详情赋值
    this.order_detail = res[0].data.data.orderDetail[0];
    this.order = res[0].data.data;

    //判断订单是否重复
    if (!res[1].data.state) {
      this.$router.push("/vipmanager/charge");
      return;
    }

    //生成二维码
    let payUrl = res[1].data.code_url;
    qr.toDataURL(payUrl, (err, imgBase64Url) => {
      if (err) {
        this.$messageBox.error(err);
        return;
      }
      this.imgBase64Url = imgBase64Url;
      this.qrLoading = false;
      this.qrUrl = imgBase64Url;
    });
  },
  beforeDestroy(){
    //清空定时器
    clearInterval(this.queryInterval)
  }
};
</script>